<template>
  <el-form
    ref="form"
    label-position="top"
    :model="form"
    :rules="rules"
    class="bold-label form-border"
  >
    <el-form-item label="群组名" prop="title" ref="title">
      <el-input v-model.trim="form.title" placeholder="请输入群组名" />
    </el-form-item>
    <el-form-item label="群组描述">
      <el-input v-model.trim="form.desc" type="textarea" placeholder="请输入群组描述" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="loading">保存修改</el-button>
      <el-button class="right" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import { formatGroup } from '../../format';

export default {
  name: 'settings-general', // 常规设置
  data() {
    return {
      form: JSON.parse(JSON.stringify(this.$store.state.currentGroup)),
      rules: {
        title: [{ required: true, validator: this.$va.groupTitle, trigger: 'blur' }],
      },
      loading: false,
    };
  },
  methods: {
    ...mapActions({ setCurGroup: 'setCurrentGroup' }),
    // 保存修改
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.groups.update({
            groupId: this.$route.params.groupId,
            title: this.form.title,
            desc: this.form.desc,
          }).then((res) => {
            this.$message.success('保存成功');
            this.setCurGroup(formatGroup(res.data));
          }).catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 放弃修改
    cancel() {
      this.form = JSON.parse(JSON.stringify(this.$store.state.currentGroup));
      this.$emit('close');
    },
  },
};
</script>

<style></style>
